package top.hhydra.mimall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import top.hhydra.mimall.entity.Shipping;
import top.hhydra.mimall.enums.ResponseEnum;
import top.hhydra.mimall.form.ShippingForm;
import top.hhydra.mimall.mapper.ShippingMapper;
import top.hhydra.mimall.service.IShippingService;
import top.hhydra.mimall.vo.ResponseVo;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author SaiyaEmon
 * @since 2020-02-11
 */
@Service
public class ShippingServiceImpl extends ServiceImpl<ShippingMapper, Shipping> implements IShippingService {

    @Override
    public ResponseVo<Map<String, Integer>> add(Integer uid, ShippingForm form) {
        Shipping shipping = new Shipping();
        BeanUtils.copyProperties(form, shipping);
        shipping.setUserId(uid);
        int insertCount = baseMapper.insert(shipping);
        if (insertCount == 0) {
            return ResponseVo.error(ResponseEnum.ADD_SHIPPING_FAIL);
        }
        QueryWrapper<Shipping> queryWrapper = new QueryWrapper();
        queryWrapper.setEntity(shipping);
        shipping = baseMapper.selectOne(queryWrapper);

        Map<String, Integer> map = new HashMap<>();
        map.put("shippingId", shipping.getId());

        return ResponseVo.success(map);
    }

    @Override
    public ResponseVo delete(Integer uid, Integer shippingId) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", uid);
        map.put("id", shippingId);
        int deleteCount = baseMapper.deleteByMap(map);
        if (deleteCount == 0) {
            return ResponseVo.error(ResponseEnum.DELETE_SHIPPING_FAIL);
        }
        return ResponseVo.success();
    }

    @Override
    public ResponseVo update(Integer uid, Integer shippingId, ShippingForm form) {
        Shipping shipping = new Shipping();
        BeanUtils.copyProperties(form, shipping);
        shipping.setUserId(uid);
        shipping.setId(shippingId);
        int updateCount = baseMapper.updateById(shipping);
        if (updateCount == 0) {
            return ResponseVo.error(ResponseEnum.UPDATE_SHIPPING_FAIL);
        }
        return ResponseVo.success();
    }

    @Override
    public ResponseVo<IPage<Shipping>> list(Integer uid, Integer pageNum, Integer pageSize) {
        QueryWrapper<Shipping> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", uid);
        IPage<Shipping> iPage = new Page<>(pageNum, pageSize);
        iPage = baseMapper.selectPage(iPage, queryWrapper);
        return ResponseVo.success(iPage);
    }
}
